package com.beiyou.controller;

import com.beiyou.model.Activity;
import com.beiyou.model.User;
import com.beiyou.service.Uservice;
import com.beiyou.service.impl.ActivityServiceImpl;
import com.beiyou.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    private  UserServiceImpl  uservice = new UserServiceImpl();
    /**
     * 注册页面
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止乱码
        req.setCharacterEncoding("utf8");

        String userName = req.getParameter("userName");
        String student_id = req.getParameter("student_id");
        String password = req.getParameter("passWord");
        String Class = req.getParameter("Class");
        String phone_number = req.getParameter("phone_number");
        String sex = req.getParameter("sex");

        User user = new User();
        user.setUsername(userName);
        user.setStudent_id(student_id);
        user.setPassword(password);
        user.setclass(Class);
        user.setPhone_number(phone_number);
        user.setSex(sex);


        uservice.addUser(user);
        // 注册完毕后跳转到登录页面
        req.getRequestDispatcher("userLogin.jsp").forward(req,resp);
    }

    /**
     * 登录页面
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止乱码
        req.setCharacterEncoding("utf8");

        // 获取用户类型
        String userType = req.getParameter("userType");

        // 学生
        if(userType.equals("1")){
            String userName = req.getParameter("userName");
            // 该学号是否存在，以及密码是否正确

            // 将该用户名传入会话，在提交表单时使用
            HttpSession session = req.getSession();
            session.setAttribute("userName",userName);

            User user = new User();
            user.setUsername(userName);
            ActivityServiceImpl aservice = new ActivityServiceImpl();
            List<Activity> activityList = aservice.getMyActivityByCon(user);
            // 把查询出来的结果发送到页面上去
            req.setAttribute("activityList",activityList);
            req.getRequestDispatcher("MyActivityList.jsp").forward(req,resp);
        }

        // 管理员
        if(userType.equals("2")){
            // 该管理员是否存在，以及密码是否正确

            ActivityServiceImpl aservice = new ActivityServiceImpl();
            List<Activity> activityList = aservice.getAllActivity();
            // 把查询出来的结果发送到页面上去
            req.setAttribute("activityList",activityList);
            req.getRequestDispatcher("UTotalActivityList.jsp").forward(req,resp);
        }

    }
}
